package com.king.controller;

import com.github.pagehelper.PageInfo;
import com.king.pojo.User;
import com.king.service.UserService;
import com.king.vo.ResponseMsg;
import com.king.vo.UserVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2020-01-03 20:35:38
 */
@RestController
@RequestMapping("/api")
public class UserController {

    private static final Logger LOGGER= LogManager.getLogger(UserController.class);
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("user")
    public User selectOne(Integer id) {
        return userService.queryById(id);
    }

    @CrossOrigin //处理跨域请求
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ResponseMsg login(@Valid @RequestBody UserVo userVo, BindingResult bindingResult) {

        LOGGER.info("+================"+userVo.getUsername()+"+++++++++"+userVo.getPassword());

        if (!bindingResult.hasErrors()){

            LOGGER.info("========11111111111111==========");
            User login = userService.login(userVo.getUsername(), userVo.getPassword());

            if (login != null){
                LOGGER.info("========222222222222==========");
                return new ResponseMsg(200,"success",login);
            }else {
                LOGGER.info("========33333333333333333==========");
                return new ResponseMsg(201,"账号或密码错误",null);
            }
        }else {
            LOGGER.info("========4444444444444444=========");
            return new ResponseMsg(-10,"bad msg",null);
        }
    }

    /**
     * 查询多条数据
     *
     * @param page     页码
     * @param pageSize 页大小
     * @param user     实体
     * @return PageInfo<User> 分页数据集合
     */
    @GetMapping("userAll")
    public PageInfo<User> searchAll(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize, User user) {
        return userService.queryAll(page, pageSize, user);
    }

    @PostMapping("register")
    public User register(User user){

        User user1 = null;

        LOGGER.info(user.getUsername()+"================");

        user1 = userService.insert(user);

        if (user1 != null){
            return user1;
        }

        return user1;
    }

}